package CreationalPatterns;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 使用写好的组的队列
 */

public class BlockingQueueMyself {

    public static void main1(String[] args) {
        BlockingQueue<Integer>queue=new ArrayBlockingQueue<>(1000);

        Thread t1=new Thread(()->{
           while(true){
               try {
                   Integer take = queue.take();
                   System.out.println("消费者="+take);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        Thread t2=new Thread(()->{
            int count=0;
            while(true){
                try {
                    queue.put(count);
                    System.out.println("生产者="+count);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
        t1.start();
    }




    private String[] elems=null;
    private volatile int head=0;
    private volatile int tail=0;
    private volatile int size=0;
    public BlockingQueueMyself(int capacity){
        elems=new String[capacity];
    }
    void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size> elems.length){
                this.wait();
                //return;
            }
            elems[tail]=elem;
            tail++;
            if(tail>= elems.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    String take() throws InterruptedException {
       synchronized (this){
           while (size==0){
               this.wait();
               //return null;
           }
           String result=elems[head];
           head++;
           if(head>= elems.length){
               head=0;
           }
           size--;
           this.notify();
           return result;
       }
    }

    public static void main(String[] args) {
        //这里就是检验上面写的代码和main1方法一样
    }


}
